<template>
  <view class="page order-page">
    <!-- 页面头部 -->
    <view class="order-header">
      <button class="back-button" @click="goBack">←</button>
      <text class="order-title">我的测试报告</text>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      :scroll-y="true" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 下拉刷新提示 -->
      <view class="refresh-tip" v-if="refreshing">
        <text>正在刷新...</text>
      </view>

      <!-- 订单列表项 -->
      <view 
        class="order-item" 
        v-for="(order, index) in orderList" 
        :key="order.id"
        @click="viewOrderDetail(order)"
      >
        <view class="order-info">
          <view class="order-top">
            <text class="order-id">测试ID: {{ order.id }}</text>
            <text class="order-status" :class="getStatusClass(order.status)">{{ getOrderStatusText(order.status) }}</text>
          </view>
          <view class="order-middle">
            <text class="order-time">{{ order.createTime }}</text>
            <text class="order-amount">结果: {{ order.testResult }}</text>
          </view>
          <view class="order-bottom">
            <text class="order-type">{{ order.productName }}</text>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="order-actions">
          <button 
            class="action-btn view-report-btn" 
            @click.stop="viewReport(order)"
          >
          查看报告
            <!-- {{ order.status === 1 ? '查看报告' : '获取完整报告' }} -->
          </button>
          <!-- <button 
            class="action-btn view-detail-btn" 
            @click.stop="viewOrderDetail(order)"
          >
            查看详情
          </button> -->
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-tip" v-if="loadingMore">
        <text>正在加载更多...</text>
      </view>
      
      <!-- 没有更多数据提示 -->
      <view class="no-more-tip" v-if="noMoreData && !loadingMore">
        <text>没有更多测试报告了</text>
      </view>
      
      <!-- 空数据提示 -->
      <view class="empty-tip" v-if="orderList.length === 0 && !loading && !refreshing">
        <text>暂无测试报告</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/api/api.js';

export default {
  name: 'MyOrderPage',
  data() {
    return {
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      loadingMore: false,
      refreshing: false,
      noMoreData: false
    };
  },
  mounted() {
    this.loadOrderList();
  },
  methods: {
    // 加载订单列表
    async loadOrderList() {
      if (this.loading) return;
      
      this.loading = true;
      try {
        // 确保传递正确的分页参数
        // 根据后端接口要求调整参数名
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          orderByColumn: 'createTime',
          isAsc: 'desc'
        };
        
        // 如果后端使用不同的参数名，可以取消下面的注释并注释掉上面的参数
        // const params = {
        //   pageNum: this.currentPage,
        //   pageSize: this.pageSize
        // };
        console.log('发送请求，分页参数:', params);
        const res = await this.$api.getTestsList(params);
        console.log('接口响应:', res);
        
        if (res.data && res.data.code === 200) {
          const newList = res.data.rows || [];
          this.total = res.data.total || 0;
          
          // 转换测试数据格式以适配UI
          const formattedList = newList.map(test => ({
            id: test.id,
            orderNo: test.orderNO || '无订单号',
            createTime: test.testTime || test.createTime,
            amount: '0.00', // 测试数据中没有金额信息
            status: test.testHasmoreinfo === 1 ? 1 : 0, // testHasmoreinfo == 1表示已获取全部报告(已支付)，否则为待支付
            type: this.getTestTypeText(test.testType),
            productName: this.getTestTypeText(test.testType),
            productQuantity: 1,
            testResult: test.testResult || '未完成'
          }));
          
          if (this.currentPage === 1) {
            this.orderList = formattedList;
          } else {
            this.orderList = [...this.orderList, ...formattedList];
          }
          
          // 判断是否还有更多数据
          this.noMoreData = this.orderList.length >= this.total;
        } else {
          uni.showToast({
            title: res.data?.msg || '加载失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载订单列表失败:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        this.refreshing = false;
        this.loadingMore = false;
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      console.log('下拉刷新，重置分页');
      this.refreshing = true;
      this.currentPage = 1;
      this.noMoreData = false;
      await this.loadOrderList();
    },
    
    // 上拉加载更多
    async loadMore() {
      console.log('上拉加载更多，当前页:', this.currentPage);
      if (this.loadingMore || this.noMoreData) return;
      
      this.loadingMore = true;
      this.currentPage++;
      console.log('加载第', this.currentPage, '页');
      await this.loadOrderList();
    },
    
    // 查看报告
    viewReport(test) {
      // 通知父组件切换到结果页面，传递测试数据
      this.$emit('view-report', {
        id: test.id,
        testId: test.id, // 使用测试ID作为testId
        orderId: test.orderNo !== '无订单号' ? test.orderNo : null,
        price: test.amount,
        status: test.status
      });
    },
    
    // 返回上一页
    goBack() {
      this.$emit('go-back');
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      // 这里可以跳转到订单详情页面
      // uni.showToast({
      //   title: '查看订单详情功能待实现',
      //   icon: 'none'
      // });
      console.log('查看订单详情:', order);
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      // 根据testHasmoreinfo字段判断状态
      // status为1表示已获取全部报告，0表示未获取全部报告
      return status === 1 ? '已获取全部报告' : '未获取全部报告';
    },
    
    // 获取订单状态样式类
    getStatusClass(status) {
      return `status-${status}`;
    },
    
    // 获取订单类型文本
    getOrderTypeText(type) {
      const typeMap = {
        'mbti_standard': 'MBTI标准版',
        'mbti_professional': 'MBTI专业版',
        'mbti_complete': 'MBTI完整版'
      };
      return typeMap[type] || '未知类型';
    },
    
    // 获取测试类型文本
    getTestTypeText(testType) {
      const typeMap = {
        'mbti::standard': 'MBTI标准版',
        'mbti::professional': 'MBTI专业版',
        'mbti::complete': 'MBTI完整版'
      };
      return typeMap[testType] || 'MBTI测试';
    }
  }
};
</script>

<style scoped>
/* 订单页面样式 */
.order-page {
  background-image: url('https://hongcat-beta.oss-cn-chengdu.aliyuncs.com/bg.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  padding: 0;
  position: relative;
  min-height: 100vh;
}

.order-page::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 1;
}

.order-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 40rpx;
  position: relative;
  z-index: 2;
  padding-top: 53px;
}

.order-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.back-button {
  position: absolute;
  left: 40rpx;
  top: 60%;
  transform: translateY(-30%);
  background-color: transparent;
  border: none;
  font-size: 36rpx;
  color: #333;
  /* padding: 10rpx; */
  border-radius: 50%;
}

.order-list {
  position: relative;
  z-index: 2;
  width: 95%;
  margin: 0 auto;
  height: calc(100vh - 120rpx);
}

.refresh-tip, .loading-tip, .no-more-tip, .empty-tip {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 28rpx;
}

.order-item {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
}

.order-info {
  margin-bottom: 20rpx;
}

.order-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.order-id {
  font-size: 28rpx;
  color: #666;
}

.order-status {
  font-size: 26rpx;
  padding: 5rpx 15rpx;
  border-radius: 10rpx;
}

/* 状态颜色修正 */
/* status-0: 未获取全部报告 */
.status-0 {
  background-color: #fff3cd;
  color: #856404;
}

/* status-1: 已获取全部报告 */
.status-1 {
  background-color: #d4edda;
  color: #155724;
}

/* status-2: 保留状态 */
.status-2 {
  background-color: #d1ecf1;
  color: #0c5460;
}

/* status-3: 保留状态 */
.status-3 {
  background-color: #f8d7da;
  color: #721c24;
}

.order-middle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.order-time {
  font-size: 26rpx;
  color: #999;
}

.order-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.order-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-type {
  font-size: 26rpx;
  color: #333;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  width: 171%;
}

.action-btn {
  padding: 10rpx 20rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  border: none;
  min-width: 120rpx;
  text-align: center;
  align-self: flex-end;
}

.view-report-btn {
  background-color: #007aff;
  color: white;
}

.view-detail-btn {
  background-color: #f8f9fa;
  color: #333;
  border: 1rpx solid #e9ecef;
}
</style>